import { HOME_BANNER_POSTER_TIME } from '@/assets/js/config'
import { md5 } from 'js-md5'
function fullTime (date) {
  return (
    date.getFullYear() +
    '-' +
    (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1) +
    '-' +
    (date.getDate() < 10 ? '0' + date.getDate() : date.getDate())
  )
  // + ' ' + (date.getHours() < 10 ? "0" + date.getHours() : date.getHours()) + ':' + (date.getSeconds() < 10 ? "0" + date.getSeconds() : date.getSeconds()) + ':' + (date.getMinutes() < 10 ? "0" + date.getMinutes() : date.getMinutes())
}
// 判断元素类型
export const type = ele => {
  const toString = Object.prototype.toString
  const map = {
    '[object Boolean]': 'boolean',
    '[object Number]': 'number',
    '[object String]': 'string',
    '[object Function]': 'function',
    '[object Array]': 'array',
    '[object Date]': 'date',
    '[object RegExp]': 'regExp',
    '[object Undefined]': 'undefined',
    '[object Null]': 'null',
    '[object Object]': 'object',
    '[object Map]': 'map',
    '[object Set]': 'set',
    '[object Symbol]': 'symbol'
  }
  return map[toString.call(ele)]
}
// 判断空对象，空数组，空字符串
export const isEmpty = obj => {
  if (!obj) {
    return true
  }
  if (type(obj) === 'array') {
    if (!obj.length) {
      return true
    }
  }
  if (type(obj) === 'object') {
    if (JSON.stringify(obj) === '{}') {
      return true
    }
  }
  return false
}
// 判断是否是安卓设备
export const isAndroid = () => {
  return /android/i.test(navigator.userAgent.toLowerCase())
}
// 判断是否是苹果设备
export const isApple = () => {
  return /iphone|ipod|ipad|Macintosh/i.test(navigator.userAgent.toLowerCase())
}
// 判断邮箱是否正确，可以自定义邮箱后缀
export const isEmail = (email, domains) => {
  const _domains = [
    'qq.com',
    '163.com',
    '126.com',
    'vip.126.com',
    'yeah.net',
    'vip.163.com',
    '188.com',
    'sohu.com',
    'sina.cn',
    'sina.com',
    'gmail.com',
    'hotmail.com',
    'outlook.com'
  ]
  if (domains === 0) {
    domains = _domains
  }
  const reg = new RegExp('^([A-Za-z0-9._-])+@(' + domains.join('|') + ')$')
  return reg.test(email)
}
// 判断是否为手机端
export const isMobile = () => {
  return /iphone|ipod|android.*mobile|windows.*phone|blackberry.*mobile/i.test(navigator.userAgent.toLowerCase())
}
// 验证是否可以被JSON.parse
export const isJsonString = ele => {
  try {
    JSON.parse(ele)
  } catch (e) {
    return false
  }
  return true
}
// 验证是否为第二代居民身份证
export const isIDCard = card => {
  return /^[1-9][0-9]{5}(18|19|(2[0-9]))[0-9]{2}((0[1-9])|(10|11|12))(([0-2][1-9])|10|20|30|31)[0-9]{3}[0-9Xx]$/.test(
    card
  )
}
// 操作 cookie 的方案，包括查询、修改、删除
export const cookie = {
  // 判断cookie是否可用
  support () {
    if (!(document.cookie || navigator.cookieEnabled)) return false
    return true
  },
  set (name, value, config = null) {
    let data = name + '=' + encodeURIComponent(JSON.stringify(value))
    if (config === null || config === 0 ? 0 : config.hours) {
      const d = new Date()
      d.setHours(d.getHours() + (config === null || config === 0 ? 0 : config.hours))
      data += '; expires=' + d.toUTCString()
    }
    if (config === null || config === 0 ? 0 : config.path) {
      data += '; path=' + config.path
    }
    if (config === null || config === 0 ? 0 : config.domain) {
      data += '; domain=' + config.domain
    }
    if (config === null || config === 0 ? 0 : config.secure) {
      data += '; secure=' + config.secure
    }
    if (config === null || config === 0 ? 0 : config.httpOnly) {
      data += '; httpOnly=' + config.httpOnly
    }
    if (config === null || config === 0 ? 0 : config.sameSite) {
      data += '; sameSite=' + config.sameSite
    }
    document.cookie = data
  },
  // 查询 cookie
  get (name) {
    const cs = document.cookie
    const arr = cs.split(';')
    const obj = {}
    if (cs !== '') {
      for (let i = 0; i < arr.length; i++) {
        const a = arr[i].split('=')
        const key = a[0].trim()
        if (key !== '') {
          const val = decodeURIComponent(a[1])
          obj[key] = isJsonString(val) ? JSON.parse(val) : val
        }
      }
      return name ? obj[name] : obj
    } else {
      return null
    }
  },
  // 删除 cookie
  remove (name, path) {
    const _this = this
    if (arguments.length === 0) {
      const all = this.get()
      Object.keys(all).forEach(function (item) {
        _this.set(item, '', {
          hours: -1
        })
      })
    } else {
      this.set(name, path || '', {
        hours: -1
      })
    }
  }
}
// 获取浏览器滚动条位置
export const getScrollTop = () => {
  let scrollTop = 0
  if (document.documentElement && document.documentElement.scrollTop) {
    scrollTop = document.documentElement.scrollTop
  } else if (document.body) {
    scrollTop = document.body.scrollTop
  }
  return scrollTop
}
// 基于 window.requestAnimationFrame() 滚动到浏览器顶部
export const scrollToTop = () => {
  const top = document.documentElement.scrollTop || document.body.scrollTop
  if (top > 0) {
    window.requestAnimationFrame(scrollToTop)
    window.scrollTo(0, top - top / 8)
  }
}
// 获得URL中GET请求的参数值
export const urlGet = (key, href) => {
  if (!href) return null
  const querystr = href.split('?')
  if (querystr[1]) {
    const GETs = querystr[1].split('&')
    const obj = {}
    GETs.forEach(function (item) {
      const _item = item.split('=')
      obj[_item[0]] = decodeURIComponent(_item[1])
    })
    return key ? obj[key] : obj
  }
  return null
}
// 将键值对拼接成URL带参数
export const urlParams = (obj, encode = true) => {
  const urls = []
  const add = function (key, value) {
    return key + '=' + value
  }
  for (const k in obj) {
    urls.push(add(k, obj[k]))
  }
  const str = urls.join('&')
  return encode ? encodeURIComponent(str) : str
}
// 获取当前时间戳
export const timestamp = () => {
  return Number(new Date()).toString()
}
// 时间美化函数
export const timeBeauty = (timestamp, now = new Date()) => {
  let time
  if (/^(\d{1,4})(-|\/)(\d{1,2})\2(\d{1,2}) (\d{1,2}):(\d{1,2}):(\d{1,2})$/.test(timestamp)) {
    timestamp = timestamp.replace(/-/g, '/')
    time = new Date(timestamp).getTime()
  } else {
    time = Number(timestamp)
  }
  const date = new Date(time)
  const diffTime = now.getTime() - time
  const minute = 60 * 1000 // 3分钟
  const hour = 60 * 60 * 1000 // 1小时
  const day = 24 * 60 * 60 * 1000 // 1天
  const diffHour = Math.floor(diffTime / hour)
  const diffMinute = Math.floor(diffTime / minute)
  // const diffDay = Math.floor(diffTime / day);
  const diffMinuteRuslt = Math.floor((diffTime - diffHour * hour) / minute)
  let result = ''
  if (diffTime > 0) {
    if (diffTime <= minute * 3) {
      // 3分钟内
      result = '刚刚'
    } else if (diffTime > minute && diffTime <= hour) {
      // 1小时内
      result = diffMinute + '分钟前'
    } else if (diffTime > hour && diffTime <= day) {
      // 1天内
      result =
        (diffHour < 10 ? '0' + diffHour : diffHour) +
        ':' +
        (diffMinuteRuslt < 10 ? '0' + diffMinuteRuslt : diffMinuteRuslt)
    } else if (diffTime > day && diffTime <= day * 2) {
      // 2天以下
      result = '昨天'
    } else if (diffTime > day * 2) {
      // 大于2天
      result = fullTime(date)
    }
  } else {
    result = fullTime(date)
  }
  return result
}
// 存储数据到storage
export const storage = {
  set (key, data, type = 'sync', callback) {
    if (type === 'sync') {
      uni.setStorageSync(key, data)
    } else {
      uni.setStorage({
        key,
        data,
        success: () => {
          callback && callback()
        }
      })
    }
  },
  get (key, defaultValue = '', type = 'sync', callback) {
    if (type === 'sync') {
      return uni.getStorageSync(key) || defaultValue
    } else {
      uni.getStorage({
        key,
        success: res => {
          callback && callback(res.data)
        }
      })
    }
  },
  remove (key, type = 'sync', callback) {
    if (type === 'sync') {
      uni.removeStorageSync(key)
    } else {
      uni.removeStorage({
        key,
        success: res => {
          callback && callback(res.data)
        }
      })
    }
  },
  clear (type = 'sync') {
    if (type === 'sync') {
      uni.clearStorageSync()
    } else {
      uni.clearStorage()
    }
  }
}
export const format = (number) => {
  const n = Math.floor(Math.abs(number)) // 整数
  let res = ''
  const s = n.toString()
  const length = s.length
  for (let i = length - 1; i >= 0; i--) {
    const j = length - i
    if (j % 3 === 0) {
      if (i === 0) {
        res = s[i] + res
      } else {
        res = ',' + s[i] + res
      }
    } else {
      res = s[i] + res
    }
  }
  const lastR = n === number ? res : res + '.' + number.toString().split('.')[1].substr(0, 2)
  return number >= 0 ? lastR : '-' + lastR
}
// 保存图片base64
export const base64ToSave = function (base64data, FILE_BASE_NAME = 'tmp_base64src') {
  const fsm = uni.getFileSystemManager()
  return new Promise((resolve, reject) => {
    const [, format, bodyData] = /data:image\/(\w+);base64,(.*)/.exec(base64data) || []
    if (!format) {
      reject(new Error('ERROR_BASE64SRC_PARSE'))
    }
    const filePath = `${wx.env.USER_DATA_PATH}/${FILE_BASE_NAME}.${format}`
    const buffer = wx.base64ToArrayBuffer(bodyData)
    fsm.writeFile({
      filePath,
      data: buffer,
      encoding: 'binary',
      success: () => {
        resolve(filePath)
      },
      fail: () => {
        reject(new Error('ERROR_BASE64SRC_WRITE'))
      }
    })
  })
}
// 获取任意时间
export const getDate = function (date, AddDayCount = 0) {
  if (!date) {
    date = new Date()
  }
  if (typeof date !== 'object') {
    date = date.replace(/-/g, '/')
  }
  const dd = new Date(date)

  dd.setDate(dd.getDate() + AddDayCount) // 获取AddDayCount天后的日期

  const y = dd.getFullYear()
  const m = dd.getMonth() + 1 < 10 ? '0' + (dd.getMonth() + 1) : dd.getMonth() + 1 // 获取当前月份的日期，不足10补0
  const d = dd.getDate() < 10 ? '0' + dd.getDate() : dd.getDate() // 获取当前几号，不足10补0
  return {
    fullDate: y + '-' + m + '-' + d,
    year: y,
    month: m,
    date: d,
    day: dd.getDay()
  }
}
// 判断微信
export const isWeixin = function () {
  // #ifdef H5
  const ua = navigator.userAgent.toLowerCase()
  // eslint-disable-next-line eqeqeq
  const isWXWork = ua.match(/wxwork/i) == 'wxwork'
  // eslint-disable-next-line eqeqeq
  return !isWXWork && ua.match(/micromessenger/i) == 'micromessenger'
  // #endif
  // #ifdef WEIXIN-MP
  // eslint-disable-next-line no-unreachable
  return true
  // #endif
}
export const loginOutQ = function (_store, _storage) {
  const _time = _storage.get(HOME_BANNER_POSTER_TIME)
  _store.commit('setProfile', '')
  _store.commit('setToken', '')
  uni.clearStorageSync()
  _storage.set(HOME_BANNER_POSTER_TIME, _time)
}
// 活动时间转化
export const eventTimeStatus = function ({ signUpStart, signUpEnd, currentDateSDF, eventsStartTime, eventsEndTime, _change }) {
  // sign 报名时间，current 当前时间，events 活动时间
  currentDateSDF = new Date(currentDateSDF.replace(/-/g, '/')).getTime()
  if (_change) {
    const _timesign = signUpStart.replace(/-/g, '/').split('~')
    signUpStart = new Date(_timesign[0]).getTime()
    signUpEnd = new Date(_timesign[1]).getTime()
  } else {
    signUpStart = new Date(signUpStart.replace(/-/g, '/')).getTime()
    signUpEnd = new Date(signUpEnd.replace(/-/g, '/')).getTime()
  }
  if (_change) {
    const _timeevents = eventsStartTime.replace(/-/g, '/').split('~')
    eventsStartTime = new Date(_timeevents[0]).getTime()
    eventsEndTime = new Date(_timeevents[1]).getTime()
  } else {
    eventsStartTime = new Date(eventsStartTime.replace(/-/g, '/')).getTime()
    eventsEndTime = new Date(eventsEndTime.replace(/-/g, '/')).getTime()
  }
  // console.log(signUpStart, signUpEnd, currentDateSDF, eventsStartTime, eventsEndTime)
  // 当前时间小于活动报名时间：等待报名 返回 0
  if (currentDateSDF < signUpStart) {
    return {
      statusName: '报名未开始',
      type: 0,
      listShow: '报名未开始'
    }
  }
  // 当前时间在活动报名期间:粗门玩 返回1
  if (signUpStart <= currentDateSDF && signUpEnd >= currentDateSDF) {
    return {
      statusName: '粗 门 玩',
      type: 1,
      listShow: '火热报名中'
    }
  }
  // 当前时间在活动举行期间则：活动进行中
  if (currentDateSDF >= eventsStartTime && currentDateSDF <= eventsEndTime) {
    return {
      statusName: '活动进行中',
      type: 2,
      listShow: '活动进行中'
    }
  }
  // 当前时间小于活动举办的开始时间：报名结束但是活动还未开始
  if (currentDateSDF < eventsStartTime) {
    return {
      statusName: '报名已结束',
      type: 3,
      listShow: '报名已结束'
    }
  }
  // 当前时间在大于活动结束时间：活动结束 返回3
  if (currentDateSDF > eventsEndTime) {
    return {
      statusName: '活动已结束',
      type: 4,
      listShow: '活动已结束'
    }
  }
  return {}
}
// 字符串转对象
export const urlGetObj = function (url) {
  const _url = decodeURIComponent(url)
  url = _url.indexOf('?') >= 0 ? _url.split('?') : _url
  const params = url.split('&')
  const obj = {}
  for (let i = 0; i < params.length; i++) {
    const param = params[i].split('=')
    obj[param[0]] = param[1]
  }
  return obj
}
export const md5String = function (input) {
  return md5(input)
  // try {
  //   const hash = md5.arrayBuffer(new TextEncoder().encode(input))
  //   let hex = ''
  //   console.log(9999, hash)
  //   const data = new Uint8Array(hash)
  //   for (let i = 0; i < data.length; i++) {
  //     const byte = data[i]
  //     const hexByte = byte.toString(16)
  //     hex += hexByte.length === 1 ? '0' + hexByte : hexByte
  //   }
  //   return hex
  // } catch (error) {
  //   console.log(666666, error)
  //   return ''
  // }
}
